package com.pks.insurance.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.pks.insurance.dto.CustomerDto;
import com.pks.insurance.dto.VehicleDto;
import com.pks.insurance.helper.CustomerHelper;
import com.pks.insurance.helper.UserHelper;

/**
 * Registration process of the user Servlet implementation class Used for
 * Registering user profile, vehicle and retriving quote calculation
 * 
 * @author Pankaj Soni
 */
public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = Logger
			.getLogger(RegistrationServlet.class);

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected final void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		LOGGER.debug("begin");
		String task = request.getParameter("task");
		LOGGER.info("task: " + task);
		if ("profile-register".equals(task)) {
			this.profileRegister(request, response);
		} else if ("vehicle-register".equals(task))
			this.vehicleRegister(request, response);
		LOGGER.debug("end");
	}

	/*
	 * Capture the user profile details for registration
	 */
	private void profileRegister(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			LOGGER.debug("begin");
			String ssn = request.getParameter("ssn");
			String passwd = request.getParameter("passwd");
			String firstName = request.getParameter("fName");
			String lastName = request.getParameter("lName");
			String gender = request.getParameter("gender");
			String mobileNo = request.getParameter("mobileNo");
			String emailId = request.getParameter("email");
			String city = request.getParameter("city");
			String bloodGroup = request.getParameter("bloodGroup");
			String drivingLicence = request.getParameter("drivingLicence");
			String dateOfBirthString = request.getParameter("dateOfBirth");
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-M-dd");
			Date dateOfBirth = null;
			try {
				dateOfBirth = dateFormat.parse(dateOfBirthString);
			} catch (ParseException e) {
				LOGGER.error(e.getMessage());
			}

			CustomerDto customer = new CustomerDto();
			customer.setSsn(ssn);

			CustomerHelper registrationHelper = new CustomerHelper();

			boolean userExistsFlag = registrationHelper
					.isExistingUser(customer);
			if (userExistsFlag) {
				request.setAttribute("error",
						"SSN already registered, you can login directly");
				request.getRequestDispatcher("register.jsp").forward(request,
						response);
				return;
			} else {
				customer.setPasswd(passwd);
				customer.setFirstName(firstName);
				customer.setLastName(lastName);
				customer.setGender(gender);
				customer.setDateOfBirth(dateOfBirth);
				customer.setMobileNo(mobileNo);
				customer.setEmail(emailId);
				customer.setCity(city);
				customer.setBloodGroup(bloodGroup);
				customer.setDrivingLicence(drivingLicence);
			}
			LOGGER.info("regDto:" + customer);
			boolean isUserReg = registrationHelper.registerUser(customer);
			LOGGER.info("isUserReg: " + isUserReg);

			// Set ssn in session and open home page
			HttpSession session = request.getSession(false);
			session.setAttribute("ssn", customer.getSsn());
			request.getRequestDispatcher("home.jsp").forward(request, response);
		} catch (ServletException e) {
			LOGGER.error(e.getMessage());
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
		}
		LOGGER.debug("end");
	}

	/*
	 * Capture the vehicle details
	 */
	private void vehicleRegister(HttpServletRequest request,
			HttpServletResponse response) {
		LOGGER.debug("begin");
		String type = request.getParameter("type");
		String model = request.getParameter("model");
		String make = request.getParameter("make");
		String regNo = request.getParameter("regNo");
		String policyType = request.getParameter("policyType");
		String policyAmount = request.getParameter("policyAmount");
		String mfYear = request.getParameter("mfYear");
		int totalAccident = Integer.parseInt(request
				.getParameter("totalAccident"));

		HttpSession session = request.getSession(false);
		VehicleDto vehicle = new VehicleDto();
		vehicle.setSsn((String) session.getAttribute("ssn"));
		vehicle.setType(type);
		vehicle.setModel(model);
		vehicle.setMake(make);
		vehicle.setRegNo(regNo);
		vehicle.setPolicyType(policyType);
		vehicle.setPolicyAmount(Integer.parseInt(policyAmount));
		vehicle.setMfYear(mfYear);
		vehicle.setTotalAccident(totalAccident);
		vehicle.setQuoteDate(new Date());
		LOGGER.info(":vehicleDto:" + vehicle);
		boolean vehicleReg = new CustomerHelper().registerVehicle(vehicle);
		LOGGER.info("::::vehicleRegistered::::" + vehicleReg);
		this.getQuote(request, response);
		LOGGER.debug("end");
	}

	private void getQuote(HttpServletRequest request,
			HttpServletResponse response) {
		LOGGER.debug("begin");
		try {
			request.setAttribute("quote", new UserHelper()
					.getQuote((String) request.getSession(false).getAttribute(
							"ssn")));
			request.getRequestDispatcher("quote.jsp")
					.forward(request, response);
			return;
		} catch (ServletException e) {
			LOGGER.error(e.getMessage());
		} catch (IOException ex) {
			LOGGER.error(ex.getMessage());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected final void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		LOGGER.debug("begin");
		String task = request.getParameter("task");
		if ("quote".equals(task)) {
			this.getQuote(request, response);
		}
		LOGGER.debug("end");
	}
}
